package com.briup.srms.exam.web.controller;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.briup.srms.sms.bean.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.briup.srms.exam.bean.extend.QuestionExtend;
import com.briup.srms.exam.service.IQuestionService;
import com.briup.srms.exam.vm.QuestionWithOptions;
import com.jacky.base.utils.ExcelUtils;
import com.jacky.base.utils.Message;
import com.jacky.base.utils.MessageUtil;
import com.jacky.base.utils.PageVM;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: 杰普基础管理系统
 * @description: 问题的控制器类
 * @author: charles
 * @create: 2021-1-14 11:09
 **/
@Api(description="题目相关接口")
@Validated
@RestController
@RequestMapping("/exam/question")
public class QuestionController {
	@Autowired
	private IQuestionService questionService;


	@ApiOperation(value = "分页多条件获取数据字典信息")
	@GetMapping("pageQuery")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, paramType = "query"),
		@ApiImplicitParam(name = "questionBankId", value = "题库编号", required = false, paramType = "query"),
	})
	public Message pageQuery(int page, int pageSize,Long questionBankId,String type,String level,String label) {
		PageVM<QuestionExtend> pageVM = questionService.pageQuery(page, pageSize, questionBankId, type, level, label);
		return MessageUtil.success(pageVM);
	}

	@ApiOperation(value = "通过id删除")
	@ApiImplicitParams(@ApiImplicitParam(name = "id", value = "主键", paramType = "query", required = true))
	@GetMapping("deleteById")
	public Message deleteById(long id) {
		questionService.deleteById(id);
		return MessageUtil.success("删除成功");
	}

	@ApiOperation(value = "保存或更新题目信息", notes = "如果参数中包含id后端认为是更新操作，如果参数中不包含id认为是插入操作")
	@PostMapping("saveOrUpdate")
	public Message saveOrUpdate(@RequestBody QuestionWithOptions questionoOptions) {
        System.out.println("saveOrUpdate....");
        System.out.println(questionoOptions);
		questionService.saveOrUpdate(questionoOptions);
		return MessageUtil.success("更新成功");
	}

	@ApiOperation(value = "下载模板", produces = "application/octet-stream")
	@GetMapping("downloadTemplate")
	public void downloadTemplate(HttpServletResponse response) throws Exception {
		// 2. 将excel导出
		// 2.1 excel头部数据
		String[] headList = new String[] {"题型", "题干" ,"答案","答案解析","标签","分数","选项A","选项B","选项C","选项D","选项E","选项F","选项G","选项H","选项I" };
		// 2.2 属性
		String[] fieldList = new String[] {"type", "name" ,"answer","analysis","label","score","","option_1","","","","" };
		// 2.3 数据列，需要转化
		List<Map<String, Object>> dataList = new ArrayList<>();
		// 2.4 导出文件名
		String excelName = "student_template";
		// 3. 调用工具方法导出Excel
		ExcelUtils.createExcel(response, excelName, headList, fieldList, dataList);
	}


	@ApiOperation(value = "批量导入题库数据")
	@PostMapping("uploadQuestions")
	public Message uploadOldStudent(@RequestParam("file") MultipartFile file, HttpServletRequest req) throws Exception {
		File toFile = null;
		if (file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		// 解析数据
		List<List<Object>> list = ExcelUtils.readExcel(toFile);
		List<Student> students = new ArrayList<>();
		for (List<Object> props : list) {
			Student student = new Student();
			// 设置基本信息
			for (int i=0;i<props.size();i++) {
				Object prop = props.get(i);
				System.out.println(prop);
				switch (i) {
				case 0:	// 学校班级
					student.setSchoolStuClazz((String)prop);
					break;

				default:
					break;
				}
			}
			students.add(student);
		}
		// 调用业务逻辑层代码完成批量保存操作
		return MessageUtil.success("导入成功");
	}

	public void inputStreamToFile(java.io.InputStream ins, File file) {
		try {
			java.io.OutputStream os = new java.io.FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



}
